package com.nxw.springcloud.gateway.filter;

import com.nxw.springcloud.gateway.entity.CommonConstants;
import com.nxw.springcloud.gateway.entity.EnvironmentEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 * 所有请求都会执行
 */
@Component
public class RequestGlobalFilter implements GlobalFilter, Ordered {
    private static final Logger logger
            = LoggerFactory.getLogger(RequestGlobalFilter.class);
    //执行逻辑
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getHost();
        logger.info(" uri : " + uri);
        if (uri.contains("sandbox")){
             request = exchange.getRequest().mutate().header(CommonConstants.ENVIRONMENT, EnvironmentEnum.SANDBOX.getValue()).build();
        }else {
            request = exchange.getRequest().mutate().header(CommonConstants.ENVIRONMENT, EnvironmentEnum.PROD.getValue()).build();
        }

        return chain.filter(exchange.mutate().request(request).build());
    }

    //执行顺序
    @Override
    public int getOrder() {
        return -200;
    }
}
